import { defineStore } from "pinia";
import { postProxy } from "../utils/request";

export const useUserStore = defineStore("user", {
  state: () => ({
    token: localStorage.getItem("token") || "",
    userInfo: (() => {
      const info = localStorage.getItem("userInfo");
      return info ? JSON.parse(info) : null;
    })(),
    lastVisitedPath: localStorage.getItem("lastVisitedPath") || "/", // 记录最后访问的路径
    menus: [] as any[], // 动态菜单树
  }),
  actions: {
    async login({
      username,
      password,
    }: {
      username: string;
      password: string;
    }) {
      try {
        // console.log("UserStore: 开始登录请求");
        const response = await postProxy("/user/login/username", {
          username,
          password,
        });

        console.log("UserStore: 登录响应:", response);

        if (response && response.data && response.data.token) {
          this.token = response.data.token;
          this.userInfo = { username };
          localStorage.setItem("username", username);
          localStorage.setItem("token", this.token);
          localStorage.setItem("userInfo", JSON.stringify(this.userInfo));

          // console.log("UserStore: 登录成功，token已保存:", this.token);

          // 登录成功后获取用户菜单
          try {
            await this.fetchMenus();
            console.log("UserStore: 用户菜单获取成功");
          } catch (error) {
            console.error("UserStore: 获取用户菜单失败:", error);
          }

          return { success: true, data: response.data };
        } else {
          console.log("UserStore: 登录失败，响应数据无效:", response);
          return { success: false, message: response.message || "登录失败" };
        }
      } catch (error) {
        console.error("UserStore: 登录错误:", error);
        return { success: false, message: "登录请求失败" };
      }
    },

    async logout() {
      console.log("UserStore: 执行登出操作");

      // 先调用后端登出接口
      try {
        const { postWithAuth } = await import("../utils/request");
        await postWithAuth("/internal/system/manager/logout", {});
        console.log("UserStore: 后端登出接口调用成功");
      } catch (error) {
        console.error("UserStore: 后端登出接口调用失败:", error);
        // 即使后端登出失败，也要继续清理本地状态
      }

      // 清理本地状态
      this.token = "";
      this.userInfo = null;
      this.lastVisitedPath = "/"; // 退出时重置为首页
      this.menus = []; // 清空菜单数据
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("lastVisitedPath");
      localStorage.removeItem("username");

      // 使用 router 进行跳转而不是 window.location
      console.log("UserStore: 清除登录状态，准备跳转到登录页");
      // 这里不直接跳转，让路由守卫处理
    },

    // 检查是否已登录
    isLoggedIn(): boolean {
      return !!this.token;
    },

    // 获取token
    getToken(): string {
      return this.token;
    },

    // 设置token
    setToken(token: string) {
      this.token = token;
      localStorage.setItem("token", token);
    },

    // 记录当前访问的路径
    setLastVisitedPath(path: string) {
      this.lastVisitedPath = path;
      localStorage.setItem("lastVisitedPath", path);
    },

    // 获取最后访问的路径
    getLastVisitedPath(): string {
      return this.lastVisitedPath;
    },

    // 获取登录后的跳转路径
    getLoginRedirectPath(): string {
      // 如果有记录的最后访问路径且不是登录页，则跳转到该路径
      // 否则跳转到首页
      return this.lastVisitedPath !== "/login" ? this.lastVisitedPath : "/";
    },

    async fetchMenus() {
      try {
        const { postWithAuth } = await import("../utils/request");
        const res = await postWithAuth(
          "/internal/system/manager/getSysUserMenuTree",
          {}
        );
        if (res && res.code === 0 && Array.isArray(res.data)) {
          this.menus = res.data;
          return res.data;
        } else {
          this.menus = [];
          return [];
        }
      } catch (e) {
        this.menus = [];
        return [];
      }
    },
  },
});
